<?php

class Auth extends Font_Controller {
	
	protected $valid_auth = array('weibo', 'qq');
	
	public function __construct()
	{
		parent::__construct();
		$this->valid_auth = array_map('strtolower', $this->valid_auth);
	}
	
	public function access()
	{
		$type = segment(3);
		$type = strtolower($type);
		if ( ! in_array($type, $this->valid_auth))
		{
			show_error('参数不正确，认证网站不存在！');
		}
		
		$method = 'access_'.$type;
		if ( ! method_exists($this, $method))
		{
			log_message(get_class($this).' 的 '.$method.' 方法不存在！');
			show_error('网站出问题了！请赶紧联系管理员！');
		}
		
		$this->$method();
	}
	
	public function callback()
	{
		$type = segment(3);
		$type = strtolower($type);
		if ( ! in_array(strtolower, $this->valid_auth))
		{
			show_error('参数不正确，认证网站不存在！');
		}
		
		$method = 'callback_'.$type;
		if ( ! method_exists($this, $method))
		{
			log_message(get_class($this).' 的 '.$method.' 方法不存在！');
			show_error('网站出问题了！请赶紧联系管理员！');
		}
		
		$this->$method();
	}
	
	protected function access_weibo()
	{
		require_once FCPATH.APPPATH.'libraries/oauth/weibo/config.php';
		require_once FCPATH.APPPATH.'libraries/oauth/weibo/saetv2.ex.class.php';
		$o = new SaeTOAuthV2(WB_AKEY, WB_SKEY);
		$code_url = $o->getAuthorizeURL(WB_CALLBACK_URL); //oauth2.0需要这里的设置同后台设置一致
		header('Location:'.$code_url);
		exit();
	}
	
	protected function access_qq()
	{
		
	}
	
	protected function callback_weibo()
	{
		require_once FCPATH.APPPATH.'libraries/oauth/weibo/config.php';
		require_once FCPATH.APPPATH.'libraries/oauth/weibo/saetv2.ex.class.php';
		$o = new SaeTOAuthV2(WB_AKEY, WB_SKEY);
		
		if (isset($_REQUEST['code']))
		{
			$keys = array(
				'code' => $_REQUEST['code'],
				'redirect_uri' => WB_CALLBACK_URL
			);

			try
			{
				$token = $o->getAccessToken('code', $keys) ;
			}
			catch (OAuthException $e)
			{
				show_error('授权失败！');
			}
		}
		
		if ( ! isset($token))
		{
			show_error('授权失败！');
		}
		
		$c = new SaeTClientV2(WB_AKEY ,WB_SKEY ,$token['access_token']);
		
		//获取用户的uid
		$uid_get = $c->get_uid();
		$uid = $uid_get['uid'];
		
		$this->load->model('user_model');
		$this->load->model('user_bind_model');
		
		$condition = array(
			'type' => 'weibo',
			'uid' => $uid
		);
		
		$user_bind_data = $this->auth->get_one($condition, array('user_id'));
		
		$user_id = 0;
		
		if ( ! $auth_data)
		{
			$data = array(
				'uid' => $uid,
				'type' => 'weibo'
			);
			if ( ! $this->auth->insert($data))
			{
				log_message('error', '新浪微博授权失败！原因：写入user_bind表失败！');
				show_error('授权失败！');
			}
			
			//继续完善资料 用户名，密码，邮箱
			redirect('/auth/continue');
		}
		
		$this->load->model('user_model');
		
		if ( ! $this->user_model->auth_login($user_id))
		{
			show_error($this->user_model->error());
		}
	}
	
	protected function callback_qq()
	{
		
	}

}